package com.taocares.sfss.repository;

import com.mongodb.client.gridfs.model.GridFSFile;
import com.taocares.sfss.exception.InternalException;
import java.io.InputStream;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Component;

@Component
public class GridFsStorage {
	@Autowired
	private GridFsTemplate gridFsTemplate;

	public String store(InputStream stream, String name) {
		return gridFsTemplate.store(stream, name).toHexString();
	}

	public GridFsResource getFile(String id) {
		GridFSFile file = gridFsTemplate.findOne(new Query(Criteria.where("_id").is(id)));
		if (file == null) {
			throw new InternalException((new StringBuilder()).append("文件").append(id).append("不在仓库中").toString());
		} else {
			return gridFsTemplate.getResource(file);
		}
	}

	public GridFSFile findByEtag(String etag) {
		return gridFsTemplate.findOne(new Query(Criteria.where("md5").is(etag)));
	}
}
